package org.esk.dablog.dao.hibernate;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.esk.dablog.dao.CommentDAO;
import org.esk.dablog.model.Comment;
import org.esk.dablog.model.Entry;
import org.hibernate.Session;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Hibernate;

import java.util.List;
import java.util.Collections;
import java.sql.SQLException;

/**
 * This class 
 * User: esk
 * Date: Dec 12, 2006
 * Time: 6:32:43 PM
 * $Id:$
 */
@SuppressWarnings("unchecked")
public class CommentDAOImpl extends HibernateDaoSupport implements CommentDAO {


    /**
     *
     * @param c
     */
    public void saveComment(Comment c) {
        getHibernateTemplate().saveOrUpdate(c);
    }

    /**
     *
     * @param commentId
     * @return
     */
    public Comment getComment(long commentId) {
        return (Comment) getHibernateTemplate().get(Comment.class, commentId);
    }

    public List<Comment> listComments(final Entry entry, final int start, final int count) {
        if(entry == null) {
            return Collections.EMPTY_LIST;
        }
        return (List<Comment>) getHibernateTemplate().executeFind(new HibernateCallback() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                Query q = session.createQuery(" from " + Comment.class.getName() + 
                        " c where c.entry.id = ?" +
                        " order by c.date");
                q.setParameter(0, entry.getId(), Hibernate.LONG);
                q.setFirstResult(start);
                q.setMaxResults(count);
                return q.list();
            }
        });
    }
}
